package com.blog.controller;

import com.blog.entity.Filter;
import com.blog.mapper.FileMapper;
import com.blog.utils.RequestUtils;
import com.blog.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

@RestController
public class UploadController {

    private FileMapper fileMapper;

    @Autowired
    public UploadController(FileMapper fileMapper) {
        this.fileMapper = fileMapper;
    }

    @PostMapping("/uploadFile")
    public Result upload(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println("进来了");
        String originalFilename = file.getOriginalFilename();
        System.out.println("文件的名称===》"+originalFilename);
        //获取文件名后缀
        String ex = originalFilename.substring(originalFilename.lastIndexOf(".")+1,originalFilename.length());
        String newFileNamePrefix= UUID.randomUUID().toString();
        String newFileName=newFileNamePrefix+"."+ex;
        file.transferTo(new File("D:/upload/cms",newFileName));

        Float size =Float.parseFloat(String.valueOf(file.getSize())) / 1024;
        BigDecimal b = new BigDecimal(size);
        size = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        System.out.println("file的大小===》"+size);
        //添加到数据库
        Filter file1 = new Filter();
        file1.setFileName(originalFilename);
        file1.setFileSize(size);
        file1.setImgUrl(RequestUtils.getBasePath(request)+"upload/"+newFileName);
        file1.setGmtCreate(new Date());
        fileMapper.insert(file1);
        //最后返回的是一个可以访问的全路径
        return Result.ok(RequestUtils.getBasePath(request)+"upload/"+newFileName);
    }
}
